package com.liukai.todo_android.ui.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.liukai.todo_android.R;
import com.liukai.todo_android.common.utils.TextViewBgUtil;
import com.liukai.todo_android.entity.ItemVo;
import com.liukai.todo_android.entity.data.DataTree;
import com.liukai.todo_android.entity.data.HistoryDate;
import com.liukai.todo_android.ui.adapter.listener.OnSubItemListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/17 10:54 上午
 * @description：历史列表的适配器
 * @modified By：
 * @version: $
 */
public class HistoryRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    /**
     * 一二级列表的所有数据
     */
    private List<DataTree<HistoryDate, ItemVo>> dataTrees = new ArrayList<>();
    /**
     * 判断列表项是展开还是关闭
     */
    private List<Boolean> groupItemStatus = new ArrayList<>();
    private final Context context;
    /**
     * 查找所有方式
     */
    public final int STYLE_FIND_ALL = 0;
    /**
     * 搜索方式
     */
    public final int STYLE_SEARCH = 1;
    public int style = STYLE_FIND_ALL;
    public String keyWord = "";


    @Override
    public int getItemViewType(int position) {
        return getItemStatusByPosition(position).getViewType();
    }

    public HistoryRecyclerViewAdapter(Context _context) {
        context = _context;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        View view;
        RecyclerView.ViewHolder viewHolder = null;
        if (viewType == ItemStatus.VIEW_TYPE_GROUP_ITEM) {
            view = View.inflate(parent.getContext(), R.layout.item_history_date, null);
            viewHolder = new GroupItemViewHolder(view);
        } else if (viewType == ItemStatus.VIEW_TYPE_SUB_ITEM) {
            view = View.inflate(parent.getContext(), R.layout.item_history_schedule, null);
            viewHolder = new SubItemViewHolder(view);
        }
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

        final ItemStatus itemStatus = getItemStatusByPosition(position);
        final DataTree<HistoryDate, ItemVo> dt = dataTrees.get(itemStatus.getGroupItemIndex());
        // 一级列表数据
        HistoryDate historyDate = dt.getGroupItem();
        // 二级列表数据
        List<ItemVo> itemVoList = dt.getSubItems();
        // 根据item的状态绑定不同的数据
        if (itemStatus.getViewType() == ItemStatus.VIEW_TYPE_GROUP_ITEM) {
            // 绑定一级列表数据
            onBindGroupItemViewHolder((GroupItemViewHolder) holder, itemStatus, dt, historyDate);
        } else if (itemStatus.getViewType() == ItemStatus.VIEW_TYPE_SUB_ITEM) {
            // 绑定二级列表数据
            onBindSubItemViewHolder((SubItemViewHolder) holder, itemStatus, itemVoList);
        }

    }

    /**
     * 绑定二级列表数据
     *
     * @param holder
     * @param itemStatus
     * @param itemVoList
     */
    private void onBindSubItemViewHolder(SubItemViewHolder holder, ItemStatus itemStatus,
                                         List<ItemVo> itemVoList) {
        SubItemViewHolder subItemVh = holder;
        int subItemIndex = itemStatus.getSubItemIndex();
        ItemVo itemVo = itemVoList.get(subItemIndex);

        onBindTextView(subItemVh.tvTodoName, itemVo.getTitle(), keyWord);
        // 待办描述为空，就隐藏待办描述的组件
        if (itemVo.getDescription() != null && !"".equals(itemVo.getDescription())) {
            subItemVh.tvTodoDesc.setVisibility(View.VISIBLE);
            onBindTextView(subItemVh.tvTodoDesc, itemVo.getDescription(), keyWord);
        } else {
            subItemVh.tvTodoDesc.setVisibility(View.GONE);
        }
        subItemVh.btnMore.setOnClickListener(v -> {
            onSubItemListener.onMoreClick(v, itemVo);
        });
        subItemVh.itemView.setOnClickListener(v -> {
            onSubItemListener.onSubItemClick(v, itemVo);
        });
    }

    /**
     * 绑定TextView
     *
     * @param textView 文本框组件
     * @param text     文本框内容
     */
    private void onBindTextView(TextView textView, String text, String str) {
        textView.setText(text);
        if (style == STYLE_SEARCH && !"".equals(str) && text.contains(str)) {
            TextViewBgUtil.setTextBg(textView, text, str, context);
        }
    }

    /**
     * 绑定一级列表的数据
     *
     * @param holder
     * @param itemStatus
     * @param dt
     * @param historyDate
     */
    private void onBindGroupItemViewHolder(GroupItemViewHolder holder, ItemStatus itemStatus,
                                           DataTree<HistoryDate, ItemVo> dt, HistoryDate historyDate) {
        final GroupItemViewHolder groupItemVh = holder;
        //加载groupItem，处理groupItem控件
        onBindTextView(groupItemVh.tvDate, historyDate.getDate(), "");
        onBindTextView(groupItemVh.tvCount, "本日完成:" + historyDate.getCount(), "");
        // 一级列表的点击事件
        groupItemVh.itemView.setOnClickListener(v -> {
            int groupItemIndex = itemStatus.getGroupItemIndex();
            if (!groupItemStatus.get(groupItemIndex)) {
                //groupItem由“关闭”状态到“打开”状态
                openSubItem(groupItemIndex, groupItemVh, dt);
            } else {
                //groupItem由“打开”状态到“关闭”状态
                closeSubItem(groupItemIndex, groupItemVh, dt);
            }
        });
    }

    /**
     * 关闭二级列表
     *
     * @param groupItemIndex
     * @param groupItemVh
     * @param dt
     */
    private void closeSubItem(int groupItemIndex, GroupItemViewHolder groupItemVh,
                              DataTree<HistoryDate, ItemVo> dt) {
        groupItemVh.btnExpand.setRotation(0);
        groupItemStatus.set(groupItemIndex, false);
        notifyItemRangeRemoved(groupItemVh.getAdapterPosition() + 1, dt.getSubItems().size());
    }

    /**
     * 展开二级列表
     *
     * @param groupItemIndex
     * @param groupItemVh
     * @param dt
     */
    private void openSubItem(int groupItemIndex, GroupItemViewHolder groupItemVh,
                             DataTree<HistoryDate, ItemVo> dt) {
        groupItemVh.btnExpand.setRotation(90);
        groupItemStatus.set(groupItemIndex, true);
        notifyItemRangeInserted(groupItemVh.getAdapterPosition() + 1, dt.getSubItems().size());
    }

    @Override
    public int getItemCount() {
        int itemCount = 0;
        if (groupItemStatus.size() == 0) {
            return 0;
        }
        for (int i = 0; i < dataTrees.size(); i++) {
            if (groupItemStatus.get(i)) {
                itemCount += dataTrees.get(i).getSubItems().size() + 1;
            } else {
                itemCount++;
            }
        }
        return itemCount;
    }

    /**
     * 向外暴露设置显示数据的方法
     *
     * @param dt
     */
    public void setDataTrees(List<DataTree<HistoryDate, ItemVo>> dt) {
        this.dataTrees = dt;
        initGroupItemStatus(groupItemStatus);
        notifyDataSetChanged();
    }

    public void setDataTreesExpand(List<DataTree<HistoryDate, ItemVo>> dt, String keyWord) {
        this.dataTrees = dt;
        this.style = STYLE_SEARCH;
        this.keyWord = keyWord;
        initGroupItemExpandStatus(groupItemStatus);
        notifyDataSetChanged();
    }

    /**
     * 设置初始值，所有 groupItem 默认为关闭状态
     *
     * @param l
     */
    private void initGroupItemStatus(List l) {
        groupItemStatus = new ArrayList();
        for (int i = 0; i < dataTrees.size(); i++) {
            groupItemStatus.add(false);
        }
    }

    /**
     * 设置初始值，所有 groupItem 默认为关闭状态
     *
     * @param l
     */
    private void initGroupItemExpandStatus(List l) {
        groupItemStatus = new ArrayList();
        for (int i = 0; i < dataTrees.size(); i++) {
            groupItemStatus.add(true);
        }
    }

    /**
     * 一级列表Item
     */
    public static class GroupItemViewHolder extends RecyclerView.ViewHolder {

        public TextView tvDate;
        public TextView tvCount;
        public TextView btnExpand;

        public GroupItemViewHolder(View itemView) {
            super(itemView);
            tvDate = itemView.findViewById(R.id.date);
            tvCount = itemView.findViewById(R.id.count);
            btnExpand = itemView.findViewById(R.id.btn_expand);
        }
    }

    /**
     * 二级列表Item
     */
    public static class SubItemViewHolder extends RecyclerView.ViewHolder {

        public TextView tvTodoName;
        public TextView tvTodoDesc;
        public TextView btnMore;

        public SubItemViewHolder(View itemView) {
            super(itemView);
            tvTodoName = itemView.findViewById(R.id.todo_name);
            tvTodoDesc = itemView.findViewById(R.id.todo_desc);
            btnMore = itemView.findViewById(R.id.btn_more);
        }
    }

    /**
     * item的状态
     */
    private static class ItemStatus {

        public static final int VIEW_TYPE_GROUP_ITEM = 0;
        public static final int VIEW_TYPE_SUB_ITEM = 1;

        private int viewType;
        private int groupItemIndex = 0;
        private int subItemIndex = -1;

        public ItemStatus() {
        }

        public int getViewType() {
            return viewType;
        }

        public void setViewType(int viewType) {
            this.viewType = viewType;
        }

        public int getGroupItemIndex() {
            return groupItemIndex;
        }

        public void setGroupItemIndex(int groupItemIndex) {
            this.groupItemIndex = groupItemIndex;
        }

        public int getSubItemIndex() {
            return subItemIndex;
        }

        public void setSubItemIndex(int subItemIndex) {
            this.subItemIndex = subItemIndex;
        }
    }

    /**
     * 获取position位置上的item的状态信息
     *
     * @param position
     * @return
     */
    private ItemStatus getItemStatusByPosition(int position) {

        ItemStatus itemStatus = new ItemStatus();
        int count = 0;    //计算groupItemIndex = i 时，position最大值
        int i = 0;
        //轮询 groupItem 的开关状态
        for (i = 0; i < groupItemStatus.size(); i++) {
            //pos刚好等于计数时，item为groupItem
            if (count == position) {
                itemStatus.setViewType(ItemStatus.VIEW_TYPE_GROUP_ITEM);
                itemStatus.setGroupItemIndex(i);
                break;
                //pos大于计数时，item为groupItem(i - 1)中的某个subItem
            } else if (count > position) {

                itemStatus.setViewType(ItemStatus.VIEW_TYPE_SUB_ITEM);
                itemStatus.setGroupItemIndex(i - 1);
                itemStatus.setSubItemIndex(position - (count - dataTrees.get(i - 1).getSubItems().size()));
                break;
            }
            //无论groupItem状态是开或者关，它在列表中都会存在，所有count++
            count++;
            //当轮询到的groupItem的状态为“开”的话，count需要加上该groupItem下面的子项目数目
            if (groupItemStatus.get(i)) {
                count += dataTrees.get(i).getSubItems().size();
            }
        }

        //简单地处理当轮询到最后一项groupItem的时候
        if (i >= groupItemStatus.size()) {
            itemStatus.setGroupItemIndex(i - 1);
            itemStatus.setViewType(ItemStatus.VIEW_TYPE_SUB_ITEM);
            itemStatus.setSubItemIndex(position - (count - dataTrees.get(i - 1).getSubItems().size()));
        }

        return itemStatus;
    }

    private OnSubItemListener onSubItemListener;

    public void setOnSubItemListener(OnSubItemListener onSubItemListener) {
        this.onSubItemListener = onSubItemListener;
    }
}
